APPLICATIONS = balance
MAKEFILEREL     ?= /home/rapen/dvl/tanger-0.7.0
TANGERINCLUDE   ?= $(MAKEFILEREL)/include
INCLUDE         += -I $(TANGERINCLUDE)
STMLIBDIR       ?= /home/rapen/dvl/tinySTM-0.9.9/lib
STMSUPPORTDIR   ?= $(MAKEFILEREL)/lib/stmsupport
LLVMBUILD       ?= $(shell llvm-config --build-mode)
TANGERPASS      ?= $(MAKEFILEREL)/$(LLVMBUILD)/lib/libtanger.so
EXTRAPASSES     ?=
PASSESTORUN     ?= -tanger
PASSESTORUNPOST ?=
NATIVELIBSPRE   ?=
NATIVELIBS      += -lpthread
BASELINKOPTS    ?=
NATIVELINKOPTS  ?=
HEADERS         ?= $(wildcard $(INCLUDE)/*.h)
#CFLAGS          ?= -Wall -O0 -Wstrict-prototypes -Wuninitialized -I.
#CFLAGS          ?= -Wall -g -I.
#CFLAGS          += -Wall -I.
CFLAGS          += -Wall -O3 -I.
CXXFLAGS        += -Wall
LINKOPTS        ?=
OPT             ?= opt
#LLVMLD          ?= llvm-ld -disable-opt
LLVMLD          ?= llvm-ld
LLVMGCC         ?= llvm-gcc
LLVMGXX         ?= llvm-g++
LLVMDIS         ?= llvm-dis
LLC             ?= llc
GCC             ?= gcc
# Set this to enable debug output and statistics for the LLVM pass
#TANGERPASSOPTS ?= -debug -stats


#CFLAGS=-O2 -Wall -Wstrict-prototypes -Wuninitialized
.PHONY: all clean

all: $(APPLICATIONS)
# native binary from .bc:
$(APPLICATIONS):%: %-tangerstm.bc $(STMLIBDIR)/libtanger-stm.a
	$(LLC) -f -o $(patsubst %.bc, %.s, $<) $<
	$(GCC) -o $@ $(patsubst %.bc, %.s, $<) $(NATIVELIBSPRE) $(STMLIBDIR)/libtanger-stm.a $(NATIVELIBS) $(NATIVELINKOPTS) 

# link in .bc parts of STM
%-tangerstm.bc:%-tanger.bc $(STMLIBDIR)/libtanger-stm.bc
	$(LLVMLD) -link-as-library -o $@ $< $(STMLIBDIR)/libtanger-stm.bc $(STMSUPPORTDIR)/stmsupport.bc

# run pass over combined
%-tanger.bc: %-tangerbase.bc $(TANGERPASS)
	$(OPT) $(EXTRAPASSES) -load $(TANGERPASS) -internalize -mem2reg -raiseallocs $(PASSESTORUN) -globaldce $< -o $@.tmp.bc -f $(TANGERPASSOPTS)
#	$(OPT) $(EXTRAPASSES) -load $(TANGERPASS) -deadargelim $(PASSESTORUNPOST) $@.tmp.bc -o $@ -f $(TANGERPASSOPTS)
	$(OPT) $(EXTRAPASSES) -load $(TANGERPASS) -deadargelim $(PASSESTORUNPOST) $@.tmp.bc -o $@ -f $(TANGERPASSOPTS)

# .bc from sources
%.bc: %.c $(HEADERS)
	$(LLVMGCC) $(INCLUDE) -emit-llvm -c $(CFLAGS) -o $@ $<

#balance: balance.o butils.o
#	$(CC) $(CFLAGS) -I. -o balance balance.o butils.o $(LIBRARIES)

#balance.o: balance.c balance.h
#	$(CC) $(CFLAGS) -I. -I$(TANGER_I) -c balance.c

#butils.o: butils.c balance.h
#	$(CC) $(CFLAGS) -I. -I$(TANGER_I) -c butils.c

$(APPLICATIONS)-tangerbase.bc: $(APPLICATIONS).bc
	$(LLVMLD) -link-as-library -disable-inlining -o $@ $^

clean:
	rm -f $(APPLICATIONS) *.o *.bc *.ll *.s balance.ps balance.pdf

